package com.Glow.reggie.controller;

import com.Glow.reggie.common.BaseContext;
import com.Glow.reggie.entity.AddressBook;
import com.Glow.reggie.service.EmailSenderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.Glow.reggie.common.R;
import com.Glow.reggie.entity.User;
import com.Glow.reggie.service.UserService;
import com.Glow.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
@Api(tags = "用户登录控制类")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private EmailSenderService emailSenderService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @ApiOperation(value = "发送邮箱验证码")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "user",value = "用户邮箱信息",required = true),
//            @ApiImplicitParam(name ="session",value = "session(改用redis后已弃用)",required = true)
//    })
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String email = user.getEmail();
        log.info("user:{}",user.toString());
        if(StringUtils.isNotEmpty(email)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //调用mail，发送验证码到用户的邮箱
//先不用了，免得邮箱塞爆了
//        emailSenderService.contextLoads(code,email);

            //需要将生成的验证码保存到Session
//            session.setAttribute(email,code);
//            优化为redis，验证码存储在redis中,5分钟后删除
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
            return R.success("邮箱验证码邮件发送成功");
        }

        return R.error("邮箱验证码发送失败");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        //获取邮箱号
        String email = map.get("email").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码，作废，改用redis
//        Object codeInSession = session.getAttribute(email);
        String redisEmailCode = (String) redisTemplate.opsForValue().get(email);
        //进行验证码的比对（页面提交的验证码和redis中保存的验证码比对）
        if(code.equals(redisEmailCode)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            //删除验证码key
            redisTemplate.delete(email);
            //存储用户userId
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
    @PostMapping("loginout")
    public R<String> loginout(HttpSession httpSession)
    {
        httpSession.removeAttribute("user");
        return R.success("退出成功！");
    }

}
